package com.thrc.borrow.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.alibaba.fastjson.JSONObject;
import com.thrc.borrow.entity.Question;
import com.thrc.borrow.service.QuestionService;
import com.thrc.borrow.utils.ExcelUtil;
import com.thrc.borrow.utils.ResponseUtil;
import com.thrc.borrow.utils.ReturnCode;
import com.thrc.borrow.vo.QuestionVo;

@Controller
@RequestMapping("/question")
public class QuestionController {

	@Autowired
	private QuestionService questionService;

	@RequestMapping("/list/page")
	public String goUserJsp() {

		return "sys/questionList";
	}

	@RequestMapping("/getById")
	public void selectById(HttpServletResponse response, Question t) {
		QuestionVo vo = questionService.selectById(t);
		ResponseUtil.print(response, vo);
	}

	@RequestMapping("/selectAll")
	public void selectAll(HttpServletResponse response, Question t) {
		try {
			List<QuestionVo> UserList = questionService.selectAll(t);
			ResponseUtil.print(response, UserList);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, e.getMessage());
		}
	}

	@RequestMapping("/selectByPage")
	public void selectByPage(HttpServletResponse response, Question t) {

		JSONObject retJson = new JSONObject();
		try {
			int totleCount = questionService.selectCount(t);
			retJson.put("total", totleCount);
			if (totleCount == 0) {
				retJson.put("data", null);
				ResponseUtil.print(response, retJson);
				return;
			}
			List<QuestionVo> UserList = questionService.selectByPage(t);
			for (QuestionVo questionVo : UserList) {
				if("1".equals(questionVo.getCorrect())){
					questionVo.setCorrect("A");
				}
				if("2".equals(questionVo.getCorrect())){
					questionVo.setCorrect("B");
				}
				if("3".equals(questionVo.getCorrect())){
					questionVo.setCorrect("C");
				}
				if("4".equals(questionVo.getCorrect())){
					questionVo.setCorrect("D");
				}
				if("1".equals(questionVo.getType())){
					questionVo.setType("选择题");
				}
				if("2".equals(questionVo.getType())){
					questionVo.setType("判断题");
				}				
			}
			retJson.put("data", UserList);
			ResponseUtil.print(response, retJson);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, e.getMessage());
		}
	}

	
	@RequestMapping("/insertQuestion")
	public void insert(HttpServletResponse response, 
					   HttpServletRequest request, 
					   Question t) {

		try {
			t.setCreate_time(new Date());
			questionService.insert(t);
			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, e.getMessage());
		}
	}

	@RequestMapping("/updateQuestion")
	public void update(HttpServletResponse response, Question t) {
		try {
			questionService.update(t);
			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, e.getMessage());
		}
	}
	
	@RequestMapping("/deleteQuestion")
	public void delete(HttpServletResponse response, Question t) {

		try {
			questionService.delete(t);
			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, e.getMessage());
		}
	}
	
	@ResponseBody
	@RequestMapping("/import")
	public String importExcel(HttpServletResponse response,
			HttpServletRequest request) throws IOException{
		// 取得上传的文件
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
				.getFile("file");
		// 得到文件名称
		String realFileName = file.getOriginalFilename();
		String suffix = realFileName.substring(realFileName.indexOf("."),
				realFileName.length());

		String fileRealPath = "/upload";
		// 判断文件夹是否存在
		File targerFile = new File(fileRealPath);
		// 判断是否存在目录
		if (!targerFile.exists()) {
			targerFile.mkdirs();
		}
		String fileName = System.currentTimeMillis() + suffix;
		// 保存文件
		File uploadFile = new File(fileRealPath + fileName);
		FileCopyUtils.copy(file.getBytes(), uploadFile);
			
		List<List<Object>> excelList=ExcelUtil.readExcel(uploadFile);
		for (List<Object> list : excelList) {
			if("序号".equals(list.get(0))){
				continue;
			}
			Question ques=new Question();
			if("判断题".equals(list.get(1))){
				ques.setType("2");
				ques.setTitle(list.get(2).toString());
				ques.setAnswer_a(list.get(3).toString());
				ques.setAnswer_b(list.get(4).toString());
				ques.setCorrect(list.get(5).toString());
			}else if("选择题".equals(list.get(1))){
				ques.setType("1");
				ques.setTitle(list.get(2).toString());
				ques.setAnswer_a(list.get(3).toString());
				ques.setAnswer_b(list.get(4).toString());
				ques.setAnswer_c(list.get(5).toString());
				ques.setAnswer_d(list.get(6).toString());
				ques.setCorrect(list.get(7).toString());				
			}
			ques.setCreate_time(new Date());
			questionService.insert(ques);
		}
		
		ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);
		return null;
	}
	
	/**
	 * 根据课程id生成试卷
	 * @throws IOException 
	 */
	@RequestMapping("/generate")
	public String generateQuestions(@RequestParam(value="courseId",required=false) String courseId,
								    HttpServletResponse response, 
			                        HttpServletRequest request) throws IOException{
		//默认策略：选择题5道，判断题5道
		JSONObject obj=new JSONObject();
		
		if(StringUtils.isEmpty(courseId)){
			Question q=new Question();
			q.setType("1");
			q.setPageSize(9999);
			List<QuestionVo> questionList=questionService.selectAll(q);
			ArrayList<Integer> list1=random(questionList.size());
			List<QuestionVo> volist1=removeItem(list1,questionList);
			
			q.setType("2");
			List<QuestionVo> questionList2=questionService.selectAll(q);
			//0,1,2,3,4
			ArrayList<Integer> list2=random(questionList2.size());
			List<QuestionVo> volist2=removeItem(list2,questionList2);
			
			obj.put("1", volist1);
			obj.put("2", volist2);
		}
		response.getWriter().println(obj);
		return null;
	}
	
	public ArrayList<Integer> random(int max){
		ArrayList<Integer> list=new ArrayList<Integer>();
		
		Random random=new Random();// 定义随机类
		for (int i = 0; i < 5; i++) {
			int result=random.nextInt(max);
			list.add(result);
		}
		
		return list;
	}
	
	public List<QuestionVo> removeItem(ArrayList<Integer> items,List<QuestionVo> questionList){
		List<QuestionVo> data=new ArrayList<QuestionVo>();
		for (int i = 0; i < questionList.size(); i++) {
			for (int j = 0; j < items.size(); j++) {
				if(i==items.get(j)){
					data.add(questionList.get(i));
				}
			}
		}
		return null;
	}
}
